//
//  ViewController.swift
//  RotateArrow
//
//  Created by apple on 17/1/9.
//  Copyright © 2017年 desn. All rights reserved.
//

import UIKit

let userAnnotationIdentifer = "UserAnnotationIdentifer" //用户大头针复用标识

class ViewController: UIViewController, MAMapViewDelegate {

    var mapView: MAMapView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        initAMap()
    }

    ///初始化地图
    func initAMap() {
        mapView = MAMapView(frame: view.bounds)
        mapView.delegate = self;
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .follow
        view.addSubview(mapView!)
    }
    
    //MARK: - MapView delegate
    
    ///用户位置更新时调用此代理
    func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
        
        //取得用户大头针视图
        guard let userView = mapView.view(for: userLocation) else {
            print("没找到用户视图")
            return
        }
        
        //取方向信息
        guard let userHeading = userLocation.heading else {
            print("暂未读取到方向信息")
            return
        }
        
        //根据方向旋转箭头
        userView.rotateWithHeading(heading: userHeading)
        
    }
    
    ///返回大头针视图
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        if annotation is MAUserLocation {
            var userView = mapView.dequeueReusableAnnotationView(withIdentifier: userAnnotationIdentifer)
            if userView == nil {
                userView = MAAnnotationView(annotation: annotation, reuseIdentifier: userAnnotationIdentifer)
            }
            userView!.image = UIImage(named: "arrow")
            return userView!
        }
        return nil
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

//针对MAAnnotationView的扩展
extension MAAnnotationView {
    
    /// 根据heading信息旋转大头针视图
    ///
    /// - Parameter heading: 方向信息
    func rotateWithHeading(heading: CLHeading) {
        
        //将设备的方向角度换算成弧度
        let headings = M_PI * heading.magneticHeading / 180.0
        //创建不断旋转CALayer的transform属性的动画
        let rotateAnimation = CABasicAnimation(keyPath: "transform")
        //动画起始值
        let formValue = self.layer.transform
        rotateAnimation.fromValue = NSValue(caTransform3D: formValue)
        //绕Z轴旋转heading弧度的变换矩阵
        let toValue = CATransform3DMakeRotation(CGFloat(headings), 0, 0, 1)
        //设置动画结束值
        rotateAnimation.toValue = NSValue(caTransform3D: toValue)
        rotateAnimation.duration = 0.35
        rotateAnimation.isRemovedOnCompletion = true
        //设置动画结束后layer的变换矩阵
        self.layer.transform = toValue
        
        //添加动画
        self.layer.add(rotateAnimation, forKey: nil)
        
    }
}

